package com.houdoudou.supplier;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.houdoudou.supplier.common.Constant;
import com.houdoudou.supplier.common.HorizontalListView;
import com.houdoudou.supplier.fragment.CourierBasicFrg;
import com.houdoudou.supplier.fragment.CurrentOrderFrg;
import com.houdoudou.supplier.fragment.IndexAllFragment;
import com.houdoudou.supplier.fragment.IndexBasicFragment;
import com.houdoudou.supplier.fragment.OrderDetailFrg;
import com.houdoudou.supplier.fragment.ProductAllFragment;
import com.houdoudou.supplier.fragment.ProductBasicFragment;
import com.houdoudou.supplier.fragment.RefundTodoFrg;
import com.houdoudou.supplier.fragment.WelcomFragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SupplierMainActivity extends FragmentActivity{
	
    
	static HorizontalListView listView_second_index,listView_first_index;
	HorizontalListView listView_ActiveFrag;
	static SecondIndextAdapter second_index_adapter;
	FirstIndextAdapter first_index_adapter;
	ActivieFrgAdapter frgAdapter;
  public static Handler myMainHandler;
	
//	Fragment machinequery_fragment,supplierquery_fragment,modify_supplierpass;
//	Fragment indexbasic_fragment,indexall_fragment,productbasic_fragment,productall_fragment;
//	Fragment frg_currentorder,frg_orderDetail;
 //   Fragment current_fragment,welcome_fragment;
    FragmentManager myFragmentMan ;
    String current_Tag,last_Tag;
    Button quit;
    static String FRG_TITLE="title";
    static String FRG_TAG="tig";
    JSONArray frgJA= new JSONArray();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_supplier_main);
		myFragmentMan = getSupportFragmentManager();
		init_handler();
		listView_first_index= (HorizontalListView) findViewById(R.id.listview_first_indext);
		listView_second_index=  (HorizontalListView) findViewById(R.id.listview_second_indext);
        listView_ActiveFrag=(HorizontalListView) findViewById(R.id.listview_activefrg);
		quit=(Button) findViewById(R.id.btn_quit_act_supplier_main);
		quit.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
				SharedPreferences sharedPreferences = SupplierMainActivity.this.getSharedPreferences("config", Context.MODE_PRIVATE);
		    	   Editor editor = sharedPreferences.edit(); 	    	
		    	   editor.remove("supplier");	    	  
		    	   editor.remove("isRemember");
		    	   editor.commit();
		    	   
		    	   
				Intent intent = new Intent(SupplierMainActivity.this, LoginActivity.class);
				startActivity(intent);
				SupplierMainActivity.this.finish();
			}
		});
		first_index_adapter= new FirstIndextAdapter(this);
		listView_first_index.setAdapter(first_index_adapter);
		frgAdapter= new ActivieFrgAdapter(this);
		listView_ActiveFrag.setAdapter(frgAdapter);		
		change_second_index(0);
		
	// myFragmentMan.beginTransaction().replace(R.id.container_act_supplier_main,  new WelcomFragment()).commit();
		Message  msg= new Message();
		msg.what=2; 
		msg.arg1=100;
		msg.arg2=0;
		Bundle bundle=new Bundle();
		bundle.putString("tag", "TAG_WELCOME");
		bundle.putString("title", "欢迎");
		msg.obj=bundle;
		myMainHandler.sendMessage(msg);
	}

	
	private void init_handler(){
		myMainHandler= new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
			//	super.handleMessage(msg);
				switch(msg.what){
				case 1:{
					change_second_index(msg.arg1);
					first_index_adapter.notifyDataSetChanged();
				          break;}
			/*	case 2:{
					second_index_adapter.notifyDataSetChanged();
					switchContent(current_fragment,get_fragment(msg.arg1,msg.arg2,msg.obj));
					// showFragment(msg.arg1,msg.arg2);				
			          break;}	 */
				
			case 2:{ //新增frgment
				second_index_adapter.notifyDataSetChanged();
				Bundle bundle=(Bundle)msg.obj;		
				String frgTag=bundle.getString("tag");
				// 判断是否存在，
				Fragment frg= myFragmentMan.findFragmentByTag(frgTag);
				if(frg!=null){
					myFragmentMan.beginTransaction().remove(frg).commit();									
				}	
				frg=create_fragment(msg.arg1,msg.arg2);	
				 frg.setArguments(bundle);   //显示的时候，会报故障
				myFragmentMan.beginTransaction().add(R.id.container_act_supplier_main, frg, frgTag).commit();			  		   
		       current_Tag=frgTag;
		       
		       boolean isExist=false;
		       for(int i=0;i<frgJA.size();i++){
		    	   if(frgJA.getJSONObject(i).getString(FRG_TAG).equals(frgTag)){
		    		   isExist=true;
		    		   frgJA.getJSONObject(i).put(FRG_TITLE,bundle.getString("title"));
		    		   break;
		    	   }
		       }
		      if(!isExist){//不存在
		    	  JSONObject frgJO= new JSONObject();
				   frgJO.put(FRG_TAG, frgTag);
				   frgJO.put(FRG_TITLE,bundle.getString("title") );
				   frgJA.add(frgJO);	 
		      }  
				
				   frgAdapter.notifyDataSetChanged();
		          break;} //case 3			
			}
				 	
				
			}
			
		};
	}
	
	private void  change_second_index(int first_index_position){
		
		
		second_index_adapter= new SecondIndextAdapter( SupplierMainActivity.this,first_index_position);
		listView_second_index.setAdapter(second_index_adapter);
		second_index_adapter.notifyDataSetChanged();
	}
	
/*	public  void showFragment(int first_index_position,int second_index_positon){
		System.out.println("---------"+first_index_position+"------"+ second_index_positon+"---------");
	     //	Fragment fragment= new MachineConfigFragment();
		 // FragmentManager fragmentManager = getSupportFragmentManager();
	      // FragmentTransaction  transaction = fragmentManager.beginTransaction();	      
		  // transaction.replace(R.id.container_act_supplier_main,  fragment).commit();
		switchContent(current_fragment,get_fragment(first_index_position,second_index_positon));
	} */
	private Fragment create_fragment(int first,int second){
		Fragment fragment =null;
		switch(first){
		case 0:{ //产品管理
	            switch(second){
	            case 0: {    return new IndexBasicFragment();}
	            
	            case 1: {   return new IndexAllFragment(); }
	            case 2: {  return new ProductBasicFragment();}
	            case 3: {  return new ProductAllFragment();}	            
	            default:{ return new WelcomFragment(); }
	            } } //first case0
		case 1:{ //订单管理
            switch(second){
              case 0: { return  new CurrentOrderFrg();}
              case 5: { return new OrderDetailFrg(); }
              default:{ return new WelcomFragment(); }
             } } //first case1	
		case 2:{ //退款管理
            switch(second){
              case 0: { return  new RefundTodoFrg();}
              default:{ return new WelcomFragment(); }
             } } //first case1	
		case 3:{ //送货员管理
            switch(second){
              case 1: { return  new CourierBasicFrg();}
              default:{ return new WelcomFragment(); }
             } } //first case1	
		default: {return new WelcomFragment(); } //first default	
		}	
	}
	
	
	/*
	 public void switchContent(Fragment from, Fragment to) {
		 FragmentTransaction transaction = myFragmentMan.beginTransaction(); 
	        if (current_fragment != to) {
	          //  FragmentTransaction transaction = myFragmentMan.beginTransaction().setCustomAnimations(
	            //        android.R.anim.fade_in, android.R.anim.fade_out);           
	            if (!to.isAdded()) {    // 先判断是否被add过
	                transaction.hide(from).add(R.id.container_act_supplier_main, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
	            } else {
	                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
	            }
	            current_fragment = to;
	        }else{
	        	 transaction.hide(from).show(from).commit(); 
	        }
	    }
*/	

	 
	 private class ActivieFrgAdapter extends BaseAdapter {
			Context context;
			
			private LayoutInflater mInflater; 
			
			
			public ActivieFrgAdapter(Context context) {
				
				 mInflater=LayoutInflater.from(context);  
			
			}		   
			    private class ViewHolder {  
			        private TextView title ;  
			        private ImageView delete;
			        private LinearLayout lt;
			    }  
			
			 @Override  
			    public int getCount() {  
			        return frgJA.size();  
			    }  
			     
			    @Override  
			    public Object getItem(int position) {  
			        return frgJA.getJSONObject(position);  
			    }  
			   
			    @Override  
			    public long getItemId(int position) {  
			        return position;  
			    }  
			  
			    @Override  
			    public View getView(int position, View convertView, ViewGroup parent) {  
			     final int selectedID=position;
			     ViewHolder vh    =new ViewHolder();  
			        if(convertView==null){  
			            convertView = mInflater.inflate(R.layout.list_activiefrg, null);  
			           vh.lt= (LinearLayout) convertView.findViewById(R.id.lt_listactivefrg);
			           vh.title= (TextView) convertView.findViewById(R.id.tv_title_listactivefrg);
			           vh.delete= (ImageView) convertView.findViewById(R.id.img_delete_listactivefrg);
			            convertView.setTag(vh);  
			        }else{  
			            vh=(ViewHolder)convertView.getTag();  
			        }  
			        vh.title.setText(frgJA.getJSONObject(selectedID).getString(FRG_TITLE)); 
			        final String tagNow=frgJA.getJSONObject(selectedID).getString(FRG_TAG);
			        
			        Fragment frgTHIS =myFragmentMan.findFragmentByTag(tagNow);
			        
			        if(tagNow.equals(current_Tag)){ 	        
			        	vh.lt.setBackgroundResource(R.drawable.second_index_selected_style);
			        	vh.delete.setVisibility(View.VISIBLE);	    	        	
			        	if(frgTHIS!=null){
							myFragmentMan.beginTransaction().show(frgTHIS).commit();}
			        	}else{
			        		vh.lt.setBackgroundResource(R.color.canvas_color);
			        		vh.delete.setVisibility(View.INVISIBLE);	
			        		if(frgTHIS!=null){
								myFragmentMan.beginTransaction().hide(frgTHIS).commit();}
			        	}
			      
			        
			        vh.title.setOnClickListener(new View.OnClickListener() {				
						@Override
						public void onClick(View v) {
							if(tagNow.equals(current_Tag)) return;						
							last_Tag=current_Tag;
							current_Tag=tagNow;
							frgAdapter.notifyDataSetChanged();
						}
					});
			        vh.delete.setOnClickListener(new View.OnClickListener() {				
						@Override
						public void onClick(View v) {					 						
							Fragment frg_this= myFragmentMan.findFragmentByTag(tagNow);										
							if(frg_this!=null){
								myFragmentMan.beginTransaction().remove(frg_this).commit();
							}
							frgJA.remove(selectedID);						
							if(selectedID>=1){
								current_Tag=frgJA.getJSONObject(selectedID-1).getString(FRG_TAG);	
								frgAdapter.notifyDataSetChanged();		
							 }else{
								 if(frgJA.size()>=1){
									 current_Tag=frgJA.getJSONObject(frgJA.size()-1).getString(FRG_TAG);	
									 frgAdapter.notifyDataSetChanged(); 
								 }
							 }
						}
					});
			        return convertView;  
			    }  
	
            }
}
